/*
 *  atBudget Personal Finance Management application
 *
 *  Copyright 2011, Ilia Frenkel <frenkel.ilia@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
	Transactions list. This list is used in the main view when user selects
	one of the accounts. It shows the list of all transactions for the
	selected account that can be filtered.
 */
Ext.define('ATB.view.transaction.List' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.transactionlist',
	store : 'Transactions',
    title : 'Transactions',
	hideHeaders: false,
	viewConfig: {
		emptyText: '<p style="text-align:center;color:#999999;font-weight: '+
			'bold;font-size:120%;margin-top:2em">There are no transactions '+
			'for this account yet.</p>',
		singleSelect: true,
		allowDeselect: true,
		stripeRows: true
	},//viewConfig
	dockedItems: [{//menu
		xtype: 'toolbar',
		style: {borderTop: 'none'},
		dock: 'top',
		weight: 1,
		defaults: {
			iconAlign: 'left'
		},
		items: [{
			text: 'Add',
			icon: 'res/img/icon-add16x16.gif',
			action: 'addtransaction',
			disabled: true
		}, ' ', {
			text: 'Edit',						
			icon: 'res/img/icon-edit16x16.png',
			action: 'edittransaction',
			disabled: true
		}, '-', {
			text: 'Remove',
			icon: 'res/img/icon-delete16x16.png',
			action: 'deletetransaction',
			disabled: true
		}, ' ', '-', ' ', {
			text: 'Quick entry',
			icon: 'res/img/icon-lightning16x16.png',
			tooltip: 'Show/hide quick entry form',
			action: 'showhidequickentry',			
			enableToggle: true,
			pressed: true
		}]
	}, { //quick entry
		xtype: 'toolbar',
		name: 'quickentryform',
		dock: 'bottom',
		weight: 1,
		layout: 'hbox',
		defaults: {
			margins: '2 2 8 2'
		},
		items: [{
			xtype: 'tbtext',
			text: 'Quick entry: ',
			style: {
				fontSize: '120%',
				fontWeight: 'bold'
			}
		}, {
			xtype: 'form',
			flex: 1,
			bodyStyle: {
				background: 'transparent'
			},
			border: false,
			layout: {
				type: 'hbox',
				pack: 'left'
			},
			defaults: {
				margin: '2 1'
			},
			items: [{
				xtype: 'fieldcontainer',
				fieldLabel: '',
				labelAlign: 'top',
				layout: {
					type: 'hbox',
					align: 'left'
				},
				width: 200,
				defaults: {
					margin: '0 1'
				},
				fieldDefaults: {
					msgTarger: 'under',
					labelAlign: 'top'
				},
				items: [{
					xtype: 'button',
					icon: 'res/img/icon-minus16x16.png',
					text: '',
					tooltip: 'Debit',
					enableToggle: true,
					pressed: true,
					name: 'isdebit',
					listeners: {
						'toggle': function (btn, isPressed, opts) {
							if (isPressed) {
								this.setIcon('res/img/icon-minus16x16.png');
								this.setTooltip('Debit');
							} else {
								this.setIcon('res/img/icon-plus16x16.png');
								this.setTooltip('Credit');
							}
						}
					}
				}, {
					xtype    : 'numberfield',
					hideTrigger: true,
					flex: 2,
					name     : 'amount',
					labelAlign: 'top',
					allowBlank: false,
					emptyText: 'Enter amount'
				}]
			}, {
				xtype: 'categoryselect',
				name : 'category',
				fieldLabel: '',
				labelAlign: 'top',
				allowBlank: false,
				forceSelection: true,
				typeAhead: true,
				store: 'Categories',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'id',
				emptyText: 'Select category',
				width: 200
			}, {
				xtype: 'combo',
				name : 'payee',
				fieldLabel: '',
				labelAlign: 'top',
				allowBlank: false,
				forceSelection: true,
				store: 'Payees',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'id',
				emptyText: 'Select payee'
			}, {
				xtype: 'combo',
				name : 'account',
				fieldLabel: '',
				allowBlank: true,
				editable: false,
				forceSelection: true,
				store: 'Accounts',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'id',
				emptyText: 'Select account',
				enableKeyEvents: true,
				listeners: {
					'keyup': function(field, evnt, opts) {
						if(evnt.keyCode == 46) {
							field.reset();
						}
					}
				}
			}, {
				xtype: 'button',
				icon: 'res/img/icon-add16x16.gif',
				iconAlign: 'left',
				fieldLabel: '',
				text: 'Enter',
				tooltip: 'Create new transaction',
				action: 'newtransaction',
				disabled: true
			}]
		}]
	}, {//table footer
		xtype: 'toolbar',
		name: 'tablefooter',
		dock: 'bottom',
		weight: 2,
		style: {
			background: 'none',
			backgroundColor: 'transparent',
		},
		items: ['->',{
			xtype: 'tbtext',
			text: 'Account balance:',
			style: {
				fontSize: '130%',
				fontFamily: '"Times New Roman", Serif',
				fontVariant: 'small-caps',
				fontWeight: 'bold',
				color: '#777777'
			}
		}, {
			xtype: 'tbtext',
			text: '$000.00',
			name: 'accountbalance',
			style: {
				fontSize: '130%',
				fontFamily: '"Times New Roman", Serif',
				fontVariant: 'small-caps',
				fontWeight: 'bold',
				color: '#777777'
			}
		}]
	}],//dockedItems
/*
	rbar : {
		//style: {borderTop: 'none'},
		weight: 1,
		defaults: {
			iconAlign: 'top',
			minWidth: 32,
			scale: 'medium',
			iconCls: 'atb-txlist-tbicon'
		},
		items: [{
			text: 'Add',
			icon: 'res/img/icon-add16x16.gif',
			action: 'addtransaction',
			disabled: true
		}, ' ', {
			text: 'Edit',						
			icon: 'res/img/icon-edit16x16.png',
			action: 'edittransaction',
			disabled: true
		},'-', {
			text: 'Remove',
			icon: 'res/img/icon-delete16x16.png',
			action: 'deletetransaction',
			disabled: true
		}]
	},//rbar
	tbar: {
		itemId: 'txlistTopBar',
		weight: 2,
		layout: 'hbox',
		defaults: {
			margins: '2 2 8 2'
		},
		items: [{
			xtype: 'tbtext',
			text: 'Quick entry: ',
			style: {
				fontSize: '120%',
				fontWeight: 'bold'
			}
		}, {
			xtype: 'form',
			flex: 1,
			bodyStyle: {
				background: 'transparent'
			},
			border: false,
			layout: {
				type: 'hbox',
				pack: 'left'
			},
			defaults: {
				margin: '2 1'
			},
			items: [{
				xtype: 'fieldcontainer',
				fieldLabel: '',
				labelAlign: 'top',
				layout: {
					type: 'hbox',
					align: 'left'
				},
				width: 200,
				defaults: {
					margin: '0 1'
				},
				fieldDefaults: {
					msgTarger: 'under',
					labelAlign: 'top'
				},
				items: [{
					xtype: 'button',
					icon: 'res/img/icon-minus16x16.png',
					text: '',
					tooltip: 'Debit',
					enableToggle: true,
					pressed: true,
					name: 'isdebit',
					listeners: {
						'toggle': function (btn, isPressed, opts) {
							if (isPressed) {
								this.setIcon('res/img/icon-minus16x16.png');
								this.setTooltip('Debit');
							} else {
								this.setIcon('res/img/icon-plus16x16.png');
								this.setTooltip('Credit');
							}
						}
					}
				}, {
					xtype    : 'numberfield',
					hideTrigger: true,
					flex: 2,
					name     : 'amount',
					labelAlign: 'top',
					allowBlank: false,
					emptyText: 'Enter amount'
				}]
			}, {
				xtype: 'categoryselect',
				name : 'category',
				fieldLabel: '',
				labelAlign: 'top',
				allowBlank: false,
				forceSelection: true,
				typeAhead: true,
				store: 'Categories',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'id',
				emptyText: 'Select category',
				width: 200
			}, {
				xtype: 'combo',
				name : 'payee',
				fieldLabel: '',
				labelAlign: 'top',
				allowBlank: false,
				forceSelection: true,
				store: 'Payees',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'id',
				emptyText: 'Select payee'
			}, {
				xtype: 'combo',
				name : 'account',
				fieldLabel: '',
				allowBlank: true,
				editable: false,
				forceSelection: true,
				store: 'Accounts',
				queryMode: 'local',
				displayField: 'name',
				valueField: 'id',
				emptyText: 'Select account',
				enableKeyEvents: true,
				listeners: {
					'keyup': function(field, evnt, opts) {
						if(evnt.keyCode == 46) {
							field.reset();
						}
					}
				}
			}, {
				xtype: 'button',
				icon: 'res/img/icon-add16x16.gif',
				iconAlign: 'left',
				fieldLabel: '',
				text: 'Enter',
				tooltip: 'Create new transaction',
				action: 'newtransaction',
				disabled: true
			}]
		}]
	},//tbar
	
	bbar: {
		style: {
			borderLeft: 'none',
			borderRight: 'none',
			background: 'none',
			backgroundColor: 'transparent',
		},
		items: ['->',{
			xtype: 'tbtext',
			text: 'Account balance: $000.00',
			style: {
				fontSize: '130%',
				fontFamily: '"Times New Roman", Serif',
				fontVariant: 'small-caps',
				fontWeight: 'bold',
				color: '#777777'
			}
		}]
	},//bbar
*/
	bodyCls: 'atb-transactionlist',

    initComponent: function() {
        this.columns = [
            {
            	header: 'When',
            	dataIndex: 'timestamp',
            	width: 75,
            	renderer: renderTransactionDate
            }, {
            	header: 'How much',
            	dataIndex: 'amount',
            	flex: 1,
            	align: 'right',
            	renderer: renderTransactionAmount
           }, {
				header: 'What',
				dataIndex: 'fromaccount',
				flex: 2,
				sortable: false,
				renderer: renderTransactionAcc
			}, {
				header: 'Why',
				dataIndex: 'payee',
				flex: 2,
				sortable: false,
				style: {
					borderRight: 'none'
				},
				renderer: renderTransactionPayee
			}
        ];
		
        this.callParent(arguments);
    }
});

/*
 * Custom renderer for amount ("How much") column in a row in transactions list.
 * Formats value according to currency, colours negative values in red
 * and positive in green.
 */
function renderTransactionAmount(value, p, record) {
	var selectedAcc = record.store.selectedAccount;

	if (selectedAcc.data.id == record.data.fromaccount.id) {
		var aAmount = '<span style="color:#993333">'+
			selectedAcc.formatValue(-1*value)+'</span>';
	} else {
		if (record.data.rate != 0) {
			value = value / record.data.rate;
		}
		var aAmount = '<span style="color:#339933">'+
			selectedAcc.formatValue(value)+'</span>';
	}
	
	return Ext.String.format('<div class="atb-txlist-amount-cell">{0}</div>',
		aAmount);
}

/*
 * Custom renderer for date ("When") column in a row in transactions list.
 */
function renderTransactionDate(value, p, record) {
	var aDay   = Ext.util.Format.date(value,'d');
	var aMonth = Ext.util.Format.date(value,'M');
	var aTime  = Ext.util.Format.date(value,'H:i');
	var aYear  = Ext.util.Format.date(value,'Y');
	return Ext.String.format('<div class="atb-txlist-date-cell">{0}</div>',
		Ext.util.Format.date(value,'d/m/Y'));
}

/*
 * Custom renderer for accounts ("What") column in a row in transactions list.
 * Creates human readable description of where the money came from/went to.
 */
function renderTransactionAcc(value, p, record) {
	var selectedAcc = record.store.selectedAccount;
	if (selectedAcc.data.id == record.data.fromaccount.id) {
		if (record.data.toaccount) {
			var strWhat = 'Transfer to '+record.data.toaccount.name; 
		} else {
			var strWhat = 'Debit';
		}
	} else {
		if (record.data.fromaccount) {
			if (record.data.rate != 1.0) {
				var fromAcc = selectedAcc.store.getById(record.data.fromaccount.id);
				var strWhat = 'Transfer of '+fromAcc.formatValue(record.data.amount)+' from '+record.data.fromaccount.name;
			} else {
				var strWhat = 'Transfer from '+record.data.fromaccount.name;
			}
		} else {
			var strWhat = 'Credit';
		}
	}

	return Ext.String.format('<div class="atb-txlist-text-cell">{0}</div>',
		strWhat);
}

/*
 * Custom renderer for payee/category ("Why") column in a row in transactions list.
 * Creates human readable description of whom the money came from/went to.
 */
function renderTransactionPayee(value, p, record) {
	var selectedAcc = record.store.selectedAccount;
	if (selectedAcc.data.id == record.data.fromaccount.id) {
		if (record.data.toaccount) {
			var strWhy = 'Transfer money between accounts'; 
		} else {
			if (record.data.category.parentid != 0) {
				var paidFor = record.data.category.parent.name + ' / ' +
					record.data.category.name;
			} else {
				var paidFor = record.data.category.name;
			}
			var strWhy = 'Payed to <strong>'+record.data.payee.name+'</strong>'+
				' for <strong>'+paidFor+'</strong>';
		}
	} else {
		if (record.data.fromaccount) {
			var strWhy = 'Transfer money between accounts';
		} else {
			if (record.data.category.parentid != 0) {
				var paidFor = record.data.category.parent.name + ' / ' +
					record.data.category.name;
			} else {
				var paidFor = record.data.category.name;
			}
			var strWhy = 'Payed by <strong>'+record.data.payee.name+'</strong>'+
				' for <strong>'+paidFor+'</strong>';
		}
	}

	return Ext.String.format('<div class="atb-txlist-text-cell">{0}</div>',
		strWhy);
}
